﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Framework.Forms;
using Framework.Logic.Settings;

namespace Framework.Logic.Web
{
    public abstract class Download
    {
        static BukkitUpdate UpdateForm { get; set; }
        public static bool DownloadBukkitServer(string filePath, string urlDownload, bool SetServer, BukkitUpdate updateForm)
        {
            UpdateForm = updateForm;
            WebClient client = new WebClient();
            WebClient clientTwo = new WebClient();
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(filePath) + "\\plugins"))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath) + "\\plugins");
                }
                if (File.Exists(Path.GetDirectoryName(filePath) + "\\plugins\\Essentials.jar.tmp"))
                {
                    File.Delete(Path.GetDirectoryName(filePath) + "\\plugins\\Essentials.jar.tmp");
                }
                clientTwo.DownloadFile("http://tiny.cc/EssentialsZipDownload", Path.GetDirectoryName(filePath) + "\\plugins\\essentials.zip");
                using (var zip = Ionic.Zip.ZipFile.Read(Path.GetDirectoryName(filePath) + "\\plugins\\essentials.zip"))
                {
                    zip.ExtractAll(Path.GetDirectoryName(filePath) + "\\plugins", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }

                File.Delete(Path.GetDirectoryName(filePath) + "\\plugins\\essentials.zip");

                client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileAsync(new Uri(urlDownload), filePath, "bukkit");
            }
            catch (Exception)
            {
                return false;
            }

            if (SetServer)
            {
                FileSystem.SetMCServerLocation(filePath);
            }
            return true;
        }

        private static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            UpdateForm.Status = "Status: " + e.ProgressPercentage.ToString() + "% downloaded";
        }

        private static void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            UpdateForm.Status = "Status: Successfully downloaded";
            UpdateForm.EnableForm = true;
        }
    }
}